package com.hanshg.cherry.security.authentication;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.web.session.SessionInformationExpiredEvent;
import org.springframework.security.web.session.SessionInformationExpiredStrategy;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName MyExpiredSessionStrategy
 * @Description TODO
 * @Author 柠檬水
 * @Date 2020/4/27 16:59
 * @Version 1.0
 **/
@Component
@Slf4j
public class MyExpiredSessionStrategy implements SessionInformationExpiredStrategy {

    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public void onExpiredSessionDetected(SessionInformationExpiredEvent event) throws IOException, ServletException {

        Map<String, Object> map = new HashMap<>();
        map.put("code",0);
        map.put("message","您已经在另一台机器或浏览器登录，被迫下线");

        event.getResponse().setHeader("Access-Control-Allow-Origin", "*");
        event.getResponse().setHeader("Access-Control-Allow-Methods", "*");
        event.getResponse().setContentType("application/json;charset=UTF-8");

        event.getResponse().getWriter().write(objectMapper.writeValueAsString(map));
    }
}
